package com.tms.monitoring.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.tms.monitoring.service.FileUploadService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {


    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.keyid}")
    private String keyid;
    @Value("${aliyun.keysecret}")
    private String keysecret;
    @Value("${aliyun.bucketname}")
    private String bucketname;
    @Override
    public String uploadFile(MultipartFile file) {
        String url="";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint,keyid,keysecret);
        try {

            //获取文件流
            InputStream inputStream = file.getInputStream();
            //获取文件名
            String fileName = file.getOriginalFilename();
            //随机生成字符串
            String uuid=UUID.randomUUID().toString().replace("-","");
            fileName=uuid+fileName;
            //存储路径 年月日分隔
            String time=new DateTime().toString("yyyy/MM/dd");
            fileName=time+"/"+fileName;
            //上传文件
            PutObjectResult result=ossClient.putObject(bucketname,fileName,inputStream);
            //获取上传后的文件路径
            url="https://"+bucketname+"."+endpoint+"/"+fileName;
        } catch (Exception oe) {
            System.out.println("上传发生异常");
        } finally {
            //关闭
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return url;
    }
}
